import functools
from flask import g
from flask import abort
from . import security
from typing import Union
from models.users.users import Users
from models.users.roles import Roles


def certification(*args, **kwargs):
    def decorator(func):
        @functools.wraps(func)
        def inner(*func_args, **func_kwargs):

            auth: bool = kwargs.get("auth")
            role: bool = kwargs.get("role")

            # @certification(auth=True, role="admin")
            # weight = {
            #     "admin": ["admin", "operation", "inspector", "stash"],
            #     "operation": ["operation"],
            #     "inspector": ["inspector"],
            #     "stash": ["stash"]
            # }
            # if auth is False:
            #     return func(*func_args, **func_kwargs)
            # elif auth is True and role is None:
            #     if g.token is not None:
            #         return func(*func_args, **func_kwargs)
            #     else:
            #         abort(401)
            # elif auth is True and role is not None:
            #     if g.token is None:
            #         abort(401)
            #     else:
            #         user_id: int = security.decode_jwt(g.token)["user_id"]
            #         user: Users[Users, None] = g.session.query(Users).filter(Users.id == user_id).first()
            #         if user is None or user.enable is False:
            #             abort(401)
            #         db_role: Roles = g.session.query(Roles).filter(Roles.id == user_id).first()
            #
            #         weight_role: list = weight.get(db_role.role)
            #         if role in weight_role:
            #             return func(*func_args, **func_kwargs)
            #         else:
            #             abort(403)
            # else:
            #     abort(406)

            if auth is None or auth is False:
                return func(*func_args, **func_kwargs)
            else:
                if g.token is not None:
                    user_id: int = security.decode_jwt(g.token)["user_id"]
                    user: Users[Users, None] = g.session.query(Users).filter(Users.id == user_id).first()
                    if user is None or user.enable is False:
                        abort(401)
                    else:
                        return func(*func_args, **func_kwargs)
                else:
                    abort(401)

        return inner
    return decorator
